package com.cosmoplat.xikai.framework.aspectj;

import com.alibaba.fastjson2.JSONObject;
import com.cosmoplat.xikai.common.annotation.MesPermission;
import com.cosmoplat.xikai.common.exception.ServiceException;
import com.cosmoplat.xikai.framework.config.properties.MesToken;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @ClassName MESPermissionCheckAspect
 * @Description mes权限切面检查
 * @Author wdf
 * @Date 2025/1/16
 */
@Aspect
@Component
@Slf4j
public class MESPermissionCheckAspect {

    @Autowired
    private MesToken mesToken;


    private static final String MES_PERMISSION_TOKEN = "X-MES-TOKEN";

    @Before("@annotation(mesPermission)")
    public void checkPermission(JoinPoint joinPoint, MesPermission mesPermission) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

        // 获取Header中的权限校验字符
        String permissionValue = request.getHeader(MES_PERMISSION_TOKEN);
        log.info("权限字符：{}", permissionValue);
        if (permissionValue == null || !permissionValue.equals(mesToken.getToken())) {
            throw new ServiceException("Invalid or missing permission token in header");
        }
        log.info("mes请求参数:{}", JSONObject.toJSONString(joinPoint.getArgs()));
    }
}
